package com.example.campuscardmanagementsys;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpSession;
import java.sql.*;
import java.util.*;

@RestController
@CrossOrigin(origins = "http://127.0.0.1:5500", allowCredentials = "true")
@RequestMapping("/api/users")
public class UserController {

    private Connection getConnection() throws SQLException {
        String url = "jdbc:mysql://localhost:3306/BlogSystem?useSSL=false&useUnicode=true&characterEncoding=utf8";
        String user = "root";
        String password = "111111";
        return DriverManager.getConnection(url, user, password);
    }

    // 获取当前用户信息（需登录）
    @GetMapping("/me")
    public ResponseEntity<?> getCurrentUser(HttpSession session) {
        Object userId = session.getAttribute("userId");
        if (userId == null) {
            return ResponseEntity.status(401).body("未登录");
        }

        String sql = "SELECT UserID, Username, Email, Role, CreatedAt FROM Users WHERE UserID = ?";
        try (Connection conn = getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setInt(1, (int) userId);
            ResultSet rs = stmt.executeQuery();

            if (rs.next()) {
                Map<String, Object> user = new HashMap<>();
                user.put("userId", rs.getInt("UserID"));
                user.put("username", rs.getString("Username"));
                user.put("email", rs.getString("Email"));
                user.put("role", rs.getString("Role"));
                user.put("createdAt", rs.getTimestamp("CreatedAt"));
                return ResponseEntity.ok(user);
            } else {
                return ResponseEntity.status(404).body("用户不存在");
            }

        } catch (SQLException e) {
            e.printStackTrace();
            return ResponseEntity.status(500).body("服务器错误");
        }
    }

    // 管理员查看所有用户
    @GetMapping("")
    public ResponseEntity<?> getAllUsers(HttpSession session) {
        if (!isAdmin(session)) return ResponseEntity.status(403).body("无权限");

        String sql = "SELECT UserID, Username, Email, Role, CreatedAt FROM Users";
        try (Connection conn = getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql);
             ResultSet rs = stmt.executeQuery()) {

            List<Map<String, Object>> users = new ArrayList<>();
            while (rs.next()) {
                Map<String, Object> user = new HashMap<>();
                user.put("userId", rs.getInt("UserID"));
                user.put("username", rs.getString("Username"));
                user.put("email", rs.getString("Email"));
                user.put("role", rs.getString("Role"));
                user.put("createdAt", rs.getTimestamp("CreatedAt"));
                users.add(user);
            }

            return ResponseEntity.ok(users);
        } catch (SQLException e) {
            e.printStackTrace();
            return ResponseEntity.status(500).body("服务器错误");
        }
    }

    // 更新用户信息（自己或管理员）
    @PutMapping("/{userId}")
    public ResponseEntity<String> updateUser(@PathVariable int userId,
                                             @RequestBody Map<String, String> request,
                                             HttpSession session) {
        Object currentUserId = session.getAttribute("userId");
        Object currentRole = session.getAttribute("role");

        if (currentUserId == null) return ResponseEntity.status(401).body("未登录");

        boolean isAdmin = "管理员".equals(currentRole);
        if (!isAdmin && userId != (int) currentUserId) {
            return ResponseEntity.status(403).body("无权限修改他人信息");
        }

        String sql = "UPDATE Users SET Username = ?, Email = ?, UpdatedAt = NOW() WHERE UserID = ?";
        try (Connection conn = getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setString(1, request.get("username"));
            stmt.setString(2, request.get("email"));
            stmt.setInt(3, userId);

            int rows = stmt.executeUpdate();
            if (rows > 0) return ResponseEntity.ok("更新成功");
            else return ResponseEntity.status(404).body("用户不存在");

        } catch (SQLException e) {
            e.printStackTrace();
            return ResponseEntity.status(500).body("服务器错误");
        }
    }

    // 删除用户（仅管理员）
    @DeleteMapping("/{userId}")
    public ResponseEntity<String> deleteUser(@PathVariable int userId, HttpSession session) {
        if (!isAdmin(session)) return ResponseEntity.status(403).body("无权限");

        String deletePostViewsSql = "DELETE FROM PostViews WHERE PostID IN (SELECT PostID FROM Posts WHERE UserID = ?)";
        String deletePostsSql = "DELETE FROM Posts WHERE UserID = ?";
        String deleteUserSql = "DELETE FROM Users WHERE UserID = ?";

        try (Connection conn = getConnection()) {
            conn.setAutoCommit(false); // 开启事务

            try (
                    PreparedStatement deleteViewsStmt = conn.prepareStatement(deletePostViewsSql);
                    PreparedStatement deletePostsStmt = conn.prepareStatement(deletePostsSql);
                    PreparedStatement deleteUserStmt = conn.prepareStatement(deleteUserSql)
            ) {
                // 删除该用户所有博客的浏览记录
                deleteViewsStmt.setInt(1, userId);
                deleteViewsStmt.executeUpdate();

                // 删除该用户的博客
                deletePostsStmt.setInt(1, userId);
                deletePostsStmt.executeUpdate();

                // 删除该用户
                deleteUserStmt.setInt(1, userId);
                int rows = deleteUserStmt.executeUpdate();

                conn.commit(); // 提交事务

                if (rows > 0) return ResponseEntity.ok("用户及相关数据已全部删除");
                else return ResponseEntity.status(404).body("用户不存在");

            } catch (SQLException e) {
                conn.rollback(); // 出错回滚
                e.printStackTrace();
                return ResponseEntity.status(500).body("删除失败，已回滚");
            }

        } catch (SQLException e) {
            e.printStackTrace();
            return ResponseEntity.status(500).body("数据库连接失败");
        }
    }



    // 判断是否管理员
    private boolean isAdmin(HttpSession session) {
        Object role = session.getAttribute("role");
        return role != null && role.equals("管理员");
    }
}
